package com.httpClient.util;

import com.sky.JULLog.MyJulLogger;
import org.apache.http.*;
import org.apache.http.message.BasicHeaderElementIterator;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;

/**
 * date : 2024-06-20
 *
 * @author : wushikai
 */
public class ResponseUtil {

    private static Logger log = MyJulLogger.getLogger(ResponseUtil.class);

    /**
     * 使用最简单的 流式读取
     */
    public static void handleResponse(HttpResponse response) throws IOException {

        System.out.println("response 的实现类是==>" + response.getClass().getCanonicalName());
        log.info("协议版本:" + response.getProtocolVersion());
        log.info("服务器返回状态码:" + response.getStatusLine().getStatusCode());
        log.info("服务器返回状态码表述:" + response.getStatusLine().getReasonPhrase());
        log.info("服务器返回状态描述:" + response.getStatusLine().toString());

        //使用 响应头 获取 cookie 键值对,  注意这是没有被解析过的
        Header h1 = response.getFirstHeader("Set-Cookie");
        if(h1!=null ) {
            log.info(h1.toString());
        }
        Header h2 = response.getLastHeader("Set-Cookie");
        if(h2!=null ) {
            log.info(h2.toString());
        }
        Header[] hs = response.getHeaders("Set-Cookie");
        log.info(hs.length + "");

        //使用 迭代器 获取 cookie 键值对 ,  httpClient 帮你解析好;
        HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator("Set-Cookie"));
        while (it.hasNext()) {
            HeaderElement elem = it.nextElement();
            log.info(elem.getName() + " = " + elem.getValue());
            NameValuePair[] params = elem.getParameters();
            for (NameValuePair param : params) {
                log.info(" " + param);
            }
        }
        HttpEntity entity = response.getEntity();   // 返回一个 HttpResponse 的 entity(实体) 这个  实体 = 响应头+响应内容
        if (entity != null) {
            InputStream inputStream = entity.getContent();   //实体对象 获取流 , 解析data 即可;
            byte[] buffer = new byte[2048];
            while (inputStream.read(buffer) != -1) {
                log.info("第一次读取的内容是:" + new String(buffer, StandardCharsets.UTF_8));
            }
            System.out.println("\n data  read  finished.......");
            inputStream.close();

        }
    }

}
